/**
 * Created by lenovo on 2017/7/20.
 */
let DBPool = require('../dao/DBConnectPool');
let async = require('async');
let config = require('../../config');
let WXMember = require('./WXMemberController');

module.exports = {
    //新需求->先判断是否是公众号会员？
    showCardBinding: function (req, res) {
        let title = '激活';
        WXMember.getMemberInformation(req,res,function (err, code, result) {
            if(code){
                res.render('wx-404', {
                    title: title,
                    errorMessage: err
                });
            }else {
                let memberInfo = result;
                WXMember.checkPhoneNumberById(memberInfo.openid,function (err, code, result) {
                    if (code){
                        if(code == 10001){
                            WXMember.queryConfig(req,function (data) {
                                res.render('wx-activation', {
                                    title: title,
                                    success: false,
                                    sdkKey: config.amap.sdkKey,
                                    open_id: memberInfo.openid,
                                    appId: config.app.appid,
                                    sign_pkg: data.jsapi_ticket,
                                    timestamp: data.timestamp,
                                    nonceStr: data.nonceStr,
                                    signature: data.signature,
                                    ak: config.bmap.AK,
                                });
                            });
                        } else {
                            res.render('wx-404', {
                                title: title,
                                errorMessage: err
                            });
                        }
                    } else {
                        WXMember.queryConfig(req,function (data) {
                            res.render('wx-activation', {
                                title: title,
                                success: true,
                                sdkKey: config.amap.sdkKey,
                                open_id: memberInfo.openid,
                                appId: config.app.appid,
                                sign_pkg: data.jsapi_ticket,
                                timestamp: data.timestamp,
                                nonceStr: data.nonceStr,
                                signature: data.signature,
                                ak: config.bmap.AK,
                            });
                        });
                    }
                });
            }

        });
    },
    setCardBinding: function (req, res) {
        if (!req.signedCookies.userinfo ||!req.signedCookies.userinfo.openid) {
            res.json({errorMessage: '无法获取OPENID！'});
            return;
        }
        let cardTypeId = req.body.card_type_id;
        let cardTypePass = req.body.card_type_pass;
        let cardCode = req.body.card_code;
        let openId = req.signedCookies.openid;

        DBPool.getPoolConnection('mtsc', function (err, connection) {
            if (err) {
                res.json({errorMessage: '数据库链接错误'});
                connection.release();
                return;
            }
            async.waterfall([
                function (callback) {
                    let sql = 'SELECT card_type_pass ' +
                        ' FROM entity_card_type ' +
                        ' WHERE card_type_status = ? ' +
                        ' AND card_type_id= ?';
                    connection.query(sql, [1, cardTypeId], function (queryErr, rows) {
                        if (queryErr) {
                            callback(queryErr);
                        } else {
                            if (rows.length == 0) {
                                callback('您选择的实体卡类型不存在！');
                            } else if (cardTypePass != rows[0].card_type_pass) {
                                callback('您输入的绑定码错误！');
                            } else {
                                callback(null, rows[0].card_type_pass);
                            }
                        }
                    });
                },
                function (arg1, callback) {
                    let sql = 'SELECT * ' +
                        ' FROM entity_card_binding ' +
                        ' WHERE card_code = ? ' +
                        ' AND card_type_id = ? ';

                    connection.query(sql, [cardCode, cardTypeId], function (queryErr, rows) {
                        if (queryErr) {
                            callback(queryErr);
                        } else {
                            if (rows.length > 0) {
                                callback('您输入的卡号已经被绑定！');
                            } else {
                                callback(null, 0);
                            }
                        }
                    });
                },
                function (arg1, callback) {
                    let sql = 'SELECT * FROM member_user WHERE openid = ? ';
                    connection.query(sql, [openId], function (queryErr, rows) {
                        console.log('function-1');
                        if (queryErr) {
                            console.log(queryErr);
                            callback('获取用户信息失败！');
                        } else {
                            //console.log(queryErr);
                            if (rows.length == 0) {
                                callback('请注册会员！');
                            } else {
                                callback(null, rows[0].member_id);
                            }
                        }
                    });
                },
                function (arg1, callback) {
                    let date = new Date();
                    let Y = date.getFullYear() + '-';
                    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
                    let D = date.getDate() + ' ';
                    let h = date.getHours() + ':';
                    let m = date.getMinutes() + ':';
                    let s = date.getSeconds();

                    let timestamp = Y + M + D + h + m + s;

                    let sql = 'INSERT INTO entity_card_binding (card_type_id, member_id, card_code,bind_status,createtime,updatetime) ' +
                        ' VALUES ( ?, ?, ?, ?, ?, ?) ';
                    connection.query(sql, [cardTypeId, arg1, cardCode, 0, timestamp, timestamp], function (queryErr, rows) {
                        if (queryErr) {
                            console.log('debug2:', queryErr);
                            callback(queryErr);
                        } else {
                            if (rows.length > 0) {
                                callback('您输入的卡号已经被绑定！');
                            } else {
                                callback(null, 0);
                            }
                        }
                    });
                }
            ], function (err, result) {
                if (err) {
                    res.json(err);
                } else {
                    if (result == 0) {
                        res.json('绑定成功！');
                    } else {
                        res.json('绑定失败！');
                    }
                }
                connection.release();
            })
        });

    },

    showCardPackage:function (req, res) {
        let title = '我的卡包';
        WXMember.checkPhoneNumber(req,res,function (err, code, result) {
            if (code){
                if(code == 10001){
                    WXMember.queryConfig(req,function (data) {
                        res.render('wx-activation', {
                            title: '手机号绑定',

                            sdkKey: config.amap.sdkKey,
                            open_id: req.signedCookies.userinfo.openid,
                            appId: config.app.appid,
                            sign_pkg: data.jsapi_ticket,
                            timestamp: data.timestamp,
                            nonceStr: data.nonceStr,
                            signature: data.signature,
                            ak: config.bmap.AK,
                        });
                    });
                } else {
                    res.render('wx-404', {
                        title: title,
                        errorMessage: err
                    });
                }
            } else {
                DBPool.getPoolConnection('mtsc', function (err, connection) {
                    let sql = 'SELECT a.*,b.card_type_name ' +
                        ' FROM entity_card_binding as a ' +
                        ' INNER JOIN entity_card_type as b ON b.card_type_id = a.card_type_id ' +
                        ' WHERE a.member_id = ? ' +
                        ' AND b.card_type_status = ? ' +
                        ' AND a.bind_status = ? ';
                    connection.query(sql, [result.member_id, 1,0], function (queryErr, rows) {
                        if (queryErr) {
                            res.render('wx-404', {
                                title: title,
                                errorMessage: '无法获取用户信息！'
                            });
                        } else {
                            res.render('wx-cardpackage', {
                                title: title,
                                member:result,
                                cards :rows,
                            });
                        }
                        connection.release();
                    });
                });
            }
        });
    }

};
